<?php

namespace app\admin\controller\salary;

use app\common\controller\Backend;
use app\admin\model\SalaryBenchmark;
use app\admin\model\Admin;
use app\admin\model\AuthGroupAccess;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\IOFactory;
use think\Db;
/**
 * 工资基准项数据管理
 *
 * @icon fa fa-circle-o
 */
class SalaryBenchmarkData extends Backend
{

    /**
     * SalaryBenchmarkData模型对象
     * @var \app\admin\model\SalaryBenchmarkData
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\SalaryBenchmarkData;

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            $salary_id = $this->request->param('salary_id',0);
            $type = $this->request->param('type',0);//终审
            $and_where = [];
            if($salary_id){
                $and_where['salary_benchmark_id'] = $salary_id;
            }
            if($type){
                $and_where['status'] = ['in',[1,2,4,5]];
            }
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->where($and_where)
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {

                $first_trial_admin = Admin::where('id',$row->first_trial_admin_id)->field('nickname,signature')->find();
                $row->first_trial_admin_name = $first_trial_admin?$first_trial_admin['nickname']:'';
                $row->first_trial_admin_signature = $first_trial_admin?$first_trial_admin['signature']:'';

                $end_trial_admin = Admin::where('id',$row->end_trial_admin_id)->field('nickname,signature')->find();
                $row->end_trial_admin_name = $end_trial_admin?$end_trial_admin['nickname']:'';
                $row->end_trial_admin_signature = $end_trial_admin?$end_trial_admin['signature']:'';

                $row->visible(['id','admin_id','salary_benchmark_id','name','id_card','num','select_time','status',
                     'first_trial_reject_reason','first_trial_admin_name','first_trial_time',
                    'end_trial_reject_reason','end_trial_time','end_trial_admin_name','create_time','end_trial_admin_signature','first_trial_admin_signature']);
                
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        $this->assignconfig("salary_id",$this->request->param('ids'));
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                Db::startTrans();
                try {
                    $admin_info = Admin::where('id',$params['admin_id'])->find();
                    if(!$admin_info)exception('未找到用户信息');
                    $params['name'] = $admin_info['nickname'];
                    $params['id_card'] = $admin_info['id_card'];

                    $validate = $this->validate($params, 'SalaryBenchmarkData.add');
                    if ($validate !== true) exception($validate);

                    $result = $this->model->allowField(true)->save($params);
                    if (!$result) exception('添加失败');
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                $this->success();
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $salary_id = $this->request->param('salary_id');
        $staff_type = SalaryBenchmark::where('id',$salary_id)->value('staff_type');
        if(!$staff_type)$this->error('操作错误');
        $this->view->assign("staff_type", $staff_type);
        $this->view->assign("salary_id", $salary_id);
        return $this->view->fetch();
    }

    /**
     * 初审通过
     */
    public function first_trial_pass_through($ids)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            Db::startTrans();
            try {

                $res = $row->save(array('status'=>'2','first_trial_admin_id'=>$this->auth->id,'first_trial_time'=>date('Y-m-d H:i:s')));
                if (!$res)exception('审核成功');
                Db::commit();
            }  catch (\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success();
        }

        return $this->view->fetch();
    }

    /**
     * 初审驳回
     */
    public function first_trial_reject($ids = null)
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $this->token();
            $params = $this->request->post("row/a");
            if ($params) {
                Db::startTrans();
                try {
                    $params['status'] = '3';
                    $params['first_trial_admin_id'] = $this->auth->id;
                    $params['first_trial_time'] = date('Y-m-d H:i:s');
                    $result = $row->allowField(true)->save($params);
                    if(!$result)exception('驳回失败');
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                $this->success();
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


    /**
     * 终审通过
     */
    public function end_trial_pass_through($ids)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            Db::startTrans();
            try {
                $res = $row->save(array('status'=>'4','end_trial_admin_id'=>$this->auth->id,'end_trial_time'=>date('Y-m-d H:i:s')));
                if (!$res)exception('审核成功');
                Db::commit();
            }  catch (\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success();
        }

        return $this->view->fetch();
    }

    /**
     * 终审驳回
     */
    public function end_trial_reject($ids = null)
    {
        $row = $this->model->get(['id' => $ids]);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $this->token();
            $params = $this->request->post("row/a");
            if ($params) {
                Db::startTrans();
                try {
                    $params['status'] = '5';
                    $params['end_trial_admin_id'] = $this->auth->id;
                    $params['end_trial_time'] = date('Y-m-d H:i:s');
                    $result = $row->allowField(true)->save($params);
                    if(!$result)exception('驳回失败');
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                $this->success();
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }


     /**
     * 初审批量审核
     */
    public function batch_examine()
    {
        Db::startTrans();
        try {
            $idStr = $this->request->post('ids','');
            $type = $this->request->post('type','pass');
            $ids = json_decode($idStr,true);
            $first_trial_reject_reason = $this->request->post('reason','');
            if(empty($ids))exception('请勾选您需操作的内容');
            if($type != 'pass' && !$first_trial_reject_reason){
                exception('请输入原因');
            }
            if($type == 'pass'){
                foreach ($ids as $v){
                    $info = $this->model->get($v);
                    if (!$info)exception('未找到ID:'.$v.'的内容');
                    if ($info['status'] != 1)exception('ID:'.$v.'的状态不正确，请先移除');
                    $res = $info->save(array('status'=>'2','first_trial_admin_id'=>$this->auth->id,'first_trial_time'=>date('Y-m-d H:i:s')));
                    if (!$res)exception('ID:'.$v.'审核失败');
                }
            }else{
                foreach ($ids as $v) {
                    $info = $this->model->get($v);
                    if (!$info)exception('未找到ID:'.$v.'的内容');
                    if ($info['status'] != 1)exception('ID:'.$v.'的状态不正确，请先移除');
//                    $first_trial_reject_reason = '提交信息不完整';

                    $arr = array(
                        'status' => 3,
                        'first_trial_admin_id' => $this->auth->id,
                        'first_trial_time' => date('Y-m-d H:i:s'),
                        'first_trial_reject_reason' => $first_trial_reject_reason,
                    );

                    $res = $info->allowField(true)->save($arr);
                    if (!$res) exception('ID:'.$v.'驳回失败');

                }
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('操作成功');
    }

    /**
     * 终审批量审核
     */
    public function batch_examine_two()
    {
        Db::startTrans();
        try {
            $idStr = $this->request->post('ids','');
            $type = $this->request->post('type','pass');
            $end_trial_reject_reason = $this->request->post('reason','');
            if($type != 'pass' && !$end_trial_reject_reason){
                exception('请输入原因');
            }
            $ids = json_decode($idStr,true);
            if(empty($ids))exception('请勾选您需操作的内容');

            if($type == 'pass'){
                foreach ($ids as $v){
                    $info = $this->model->get($v);
                    if (!$info)exception('未找到ID:'.$v.'的内容');
                    if ($info['status'] != 2)exception('ID:'.$v.'的状态不正确，请先移除');
                    $res = $info->save(array('status'=>4,'end_trial_admin_id'=>$this->auth->id,'end_trial_time'=>date('Y-m-d H:i:s')));
                    if (!$res)exception('ID:'.$v.'审核失败');
                }
            }else{
                foreach ($ids as $v) {
                    $info = $this->model->get($v);
                    if (!$info)exception('未找到ID:'.$v.'的内容');
                    if ($info['status'] != 2)exception('ID:'.$v.'的状态不正确，请先移除');
//                    $end_trial_reject_reason = '提交信息不完整';

                    $arr = array(
                        'status' => 5,
                        'end_trial_admin_id' => $this->auth->id,
                        'end_trial_time' => date('Y-m-d H:i:s'),
                        'end_trial_reject_reason' => $end_trial_reject_reason,
                    );

                    $res = $info->allowField(true)->save($arr);
                    if (!$res) exception('ID:'.$v.'驳回失败');
                }
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('操作成功');
    }
    
    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        if ($this->request->isPost()) {

        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 导入
     */
    public function import()
    {
        $file = $this->request->request('file');
        $salary_id = $this->request->param('salary_id',0);
        $staff_type = SalaryBenchmark::where('id',$salary_id)->value('staff_type');
        if(!$staff_type)$this->error('操作错误');
        if (!$file) {
            $this->error(__('Parameter %s can not be empty', 'file'));
        }
        $filePath = ROOT_PATH . DS . 'public' . DS . $file;
        if (!is_file($filePath)) {
            $this->error(__('No results were found'));
        }
        //实例化reader
        $ext = pathinfo($filePath, PATHINFO_EXTENSION);
        if (!in_array($ext, ['csv', 'xls', 'xlsx'])) {
            $this->error(__('Unknown data format'));
        }
        if ($ext === 'csv') {
            $file = fopen($filePath, 'r');
            $filePath = tempnam(sys_get_temp_dir(), 'import_csv');
            $fp = fopen($filePath, "w");
            $n = 0;
            while ($line = fgets($file)) {
                $line = rtrim($line, "\n\r\0");
                $encoding = mb_detect_encoding($line, ['utf-8', 'gbk', 'latin1', 'big5']);
                if ($encoding != 'utf-8') {
                    $line = mb_convert_encoding($line, 'utf-8', $encoding);
                }
                if ($n == 0 || preg_match('/^".*"$/', $line)) {
                    fwrite($fp, $line . "\n");
                } else {
                    fwrite($fp, '"' . str_replace(['"', ','], ['""', '","'], $line) . "\"\n");
                }
                $n++;
            }
            fclose($file) || fclose($fp);

            $reader = new Csv();
        } elseif ($ext === 'xls') {
            $reader = new Xls();
        } else {
            $reader = new Xlsx();
        }

        $success_num = $error_num = 0;
        $msg = '';
        try {
            if (!$PHPExcel = $reader->load($filePath)) {
                $this->error(__('Unknown data format'));
            }
            $currentSheet = $PHPExcel->getSheet(0);  //读取文件中的第一个工作表
            $allColumn = $currentSheet->getHighestDataColumn(); //取得最大的列号
            $allRow = $currentSheet->getHighestRow(); //取得一共有多少行
            $maxColumnNumber = Coordinate::columnIndexFromString($allColumn);
            if($maxColumnNumber != 4)exception('文档格式不正确');
            if($allRow < 1)exception('未读取到数据');
            for ($currentRow = 2; $currentRow <= $allRow; $currentRow++) {
                $values = [];
                for ($currentColumn = 1; $currentColumn <= $maxColumnNumber; $currentColumn++) {
                    $val = $currentSheet->getCellByColumnAndRow($currentColumn, $currentRow)->getValue();
                    $values[] = is_null($val) ? '' : $val;
                }
                if(isset($values[0]) && !empty($values)){

                    $admin_info = Admin::where('id_card',$values[1])->find();
                    if(!$admin_info){
                        $error_num ++;
                        $msg .= '行号：'.$currentRow.'：身份证号未匹配上用户</br>';
                        continue;
                    }

                    $AuthGroupAccessInfo = AuthGroupAccess::where('uid',$admin_info['id'])->find();
                    if(!$AuthGroupAccessInfo){
                        $error_num ++;
                        $msg .= '行号：'.$currentRow.'：身份证号未匹配上用户身份</br>';
                        continue;
                    }

                    $check_type = $this->_check_type($staff_type,$AuthGroupAccessInfo['group_id']);
                    if(!$check_type){
                        $error_num ++;
                        $msg .= '行号：'.$currentRow.'员工身份证号和此基准项对应的员工类型不对应</br>';
                        continue;
                    }

                    $params['name'] = $admin_info['nickname'];
                    $params['id_card'] = $admin_info['id_card'];
                    $params['admin_id'] = $admin_info['id'];
                    $params['salary_benchmark_id'] = $salary_id;
                    $params['num'] = $values[2];


                    if (is_numeric($values[3])) {
                        $dateObject = \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($values[3]);
                        $values[3] = $dateObject->format('Y/m/d');
                    }else{
                        $error_num ++;
                        $msg .= '行号：'.$currentRow.'：日期格式不正确</br>';
                        continue;
                    }
                    if(date('Y/m/d', strtotime($values[3])) != $values[3]) {
                        $error_num ++;
                        $msg .= '行号：'.$currentRow.'：日期格式不正确1</br>';
                        continue;
                    }
                    $params['select_time'] = $values[3];

                    $validate = $this->validate($params, 'SalaryBenchmarkData.add');
                    if ($validate !== true){
                        $error_num ++;
                         $msg .= $values[0].'：'.$validate.'</br>';
                        continue;
                    }
                    if(Db::table('b_salary_benchmark_data')->where([
                        'id_card' => $params['id_card'],
                        'select_time' => $params['select_time'],
                        'salary_benchmark_id' => $salary_id
                    ])->count()){
                        $error_num ++;
                        $msg .= '行号：'.$currentRow.'：重复</br>';
                        continue;
                    }
                    $result = $this->model->create($params);
                  
                    if(!$result){
                        $error_num ++;
                        $msg .= '行号：'.$currentRow.'：导入失败</br>';
                        continue;
                    }else{
                        $success_num++;
                    }

                }
            }
        } catch (\Exception $exception) {
            $this->error($exception->getMessage());
        }
        $msg = '导入失败：'.$error_num.'</br>'. $msg;
        $this->success('导入成功:'.$success_num.'</br>'.$msg);
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
            try {
                $this->model->whereIn('id',$ids )->delete();
            } catch (\Exception $e) {
                $this->error($e->getMessage());
            }
            $this->success();
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    public function _check_type($staff_type,$group_id)
    {
        return true;
        if($staff_type == 1){
            if(!in_array($group_id,array(12)))return false;
        }else{
            if(!in_array($group_id,array(9,10,11,13,14)))return false;
        }
        return true;
    }
}
